package com.julinggame.nettyim;

import com.julinggame.nettyim.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * netty启动程序
 */
public class ImServer {

//    建立映射
    public static Map<String, Channel> USER_CHANNEL = new ConcurrentHashMap<>(1024);
    //启动两个线程
    public static void start() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //监听端口
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                //初始化
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //责任链
                        ChannelPipeline pipeline = ch.pipeline();
                        //http编解码器
                        pipeline.addLast(new HttpServerCodec());
                        //最大数据量支持
                        pipeline.addLast(new ChunkedWriteHandler());
                        //对http请求进行聚合，产生两个类，FullHttpRequest和FullHttpResponse
                        pipeline.addLast(new HttpObjectAggregator(1024 * 64));
                        //支持websocket协议
                        pipeline.addLast(new WebSocketServerProtocolHandler("/"));
                        pipeline.addLast(new WebSocketHandler());
                    }
                });
        ChannelFuture future = serverBootstrap.bind(8080).sync();
    }
}
